<?php

namespace App\Models\Common;

use App\Models\BaseModel;
use App\Models\Account\User;

class Password extends BaseModel
{

    protected $table = 'captchas';
    protected $fillable = ['type', 'communication', 'user_id', 'code', 'expiration_time', 'data_scope'];

    public function users()
    {
        return $this->hasMany('captchas', 'user_id');
    }

    public function addCode($data)
    {
        $auth = $this->where('communication', $data['communication'])->first();

        if ($auth) {
            $check = $this->delCode($data['communication']);
            if (!$check) {
                return null;
            }
        }

        $data['data_scope'] = $this->getDataScope();

        return $this->create($data);
    }

    public function checkEmailIsExist($communication)
    {
        $user = User::where('email', $communication)->first();

        if (!$user) {
            return null;
        }

        return $user->toArray();
    }

    public function checkPhoneIsExist($communication)
    {
        $user = User::where('phone', $communication)->first();

        if (!$user) {
            return null;
        }

        return $user->toArray();
    }

    public function getCodeInfo($data)
    {
        $res = $this->where('communication', $data['communication'])->where('code', $data['code'])->first();

        if (!$res) {
            return null;
        }

        return $res->toArray();
    }

    public function editPassword($data, $res)
    {
        $model = new User();
        $user = $model->find($res['user_id']);
        $user->password = $data['password'];
        $check = $user->save();

        if ($check) {
            $this->where('id', $res['id'])->delete();
            return $user->toArray();
        } else {
            return null;
        }
    }

    public function delCode($data)
    {
        $res = $this->where('communication', $data)->delete();

        if (!$res) {
            return null;
        }

        return $res;
    }

}
